<script setup lang="ts">

  import { getAccessToken, getTenantId } from '@/utils/auth';
  import download from "@/utils/download";

  defineOptions({ name: 'MemberImport' });

  const message = useMessage(); //消息提示
  const dialogVisible = ref(false); // 控制显示弹窗
  const formLoading = ref(false); // 加载数据蒙层
  const fileList = ref([]); // 对应的上传的文件列表
  const uploadRef = ref(); // 待上传的上传控件
  const uploadSupport = ref(0); // 后台是否要覆盖该文件
  const uploadHeaders = ref(); // 设置上传的请求头部
  import * as UserApi from '@/api/member/user'

  const importUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/member/user/import';

  const open = () => {
    dialogVisible.value = true;
    fileList.value = [];
    uploadSupport.value = 0;
    resetForm();
  };

  defineExpose({ open });

  const downloadMemberImportTemplate = async () => {
    const res = await UserApi.importPersonTemplate()
    download.excel(res, '人员导入模版.xls')
  };

  // 表单提交
  const submitForm = async () => {
    if (fileList.value.length === 0) {
      message.error('请上传文件！');
    }
    // 设置表头
    uploadHeaders.value = {
      Authorization: 'Bearer ' + getAccessToken(),
      'tenant-id': getTenantId(),
    };
    formLoading.value = true;
    try {
      uploadRef.value!.submit();
      message.success("导入成功。")
    }finally {
      formLoading.value = false;
      dialogVisible.value = false;
    }
  };

  // 重置文件上传状态,TypeScript 要求异步函数返回 Promise，
  // 显式标注 : Promise<void> 可以明确告知调用者“这是一个异步函数，无返回值”
  const resetForm = async (): Promise<void> => {
    // 重置表单的加载状态
    formLoading.value = false;
    // 当含文件上传时加nextTick(),在操作 DOM 相关逻辑（如清空文件列表）前，
    // 确保之前的响应式数据变化已生效。nextTick() 返回一个 Promise，会等待 Vue 完成当前的异步渲染队列。
    await nextTick();
    // 重置带文件列表表单
    uploadRef.value!.resetFields();
  }

</script>

<template>
  <Dialog v-model="dialogVisible" title="人员导入" width="400">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      accept=".xlsx, .xls"
      :auto-upload="false"
      :headers="uploadHeaders"
      :disabled="formLoading"
      :action="importUrl + '?uploadSupport=' + uploadSupport "
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上次</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <div class="el-upload__tip">
            <el-checkbox v-model="uploadSupport" />
            是否更新已存在的用户数据？
          </div>
          <span>仅允许导入 xls、xlsx 格式文件。</span>
          <el-link :underline="false"
                   style="font-size: 12px; vertical-align: baseline"
                   type="primary"
                   @click="downloadMemberImportTemplate"
          >下载模版
          </el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确定</el-button>
      <el-button type="warning" @click="dialogVisible = false">取消</el-button>
    </template>
  </Dialog>

</template>

<style scoped lang="scss">

</style>
